// 一. 导入express
// 二. 实例化router对象
// 三. 编写路由规则
// 四. 导出router对象

var express = require('express');
var router = express.Router();

const { getAll, getById, exec } = require('../db');
/* GET users listing. */
//获取列表所有信息
router.get('/', async function (req, res) {
  //一、编写sql语句
  let sql = 'select * from blogs';
  try {
    //二、执行sql语句，获得结果
    const data = await getAll(sql);
    //三、返回数据
    res.send({
      code: 0,
      msg: '获取所有blogs成功',
      result: data,
    });
  } catch (err) {
    res.send({
      code: 100101,
      message: '获取所有blogs失败',
      result: DEBUG ? err : '',
    });
  }
});

router.get('/:id', async function (req, res) {
  const { id } = req.params;

  let sql = `select *from blogs where id = ${id}`;
  try {
    const data = await getById(sql);
    res.send({
      code: 0,
      message: '获取单个blog成功',
      result: data,
    });
  } catch (err) {
    res.send({
      code: 100101,
      message: '获取单个blog失败',
      result: DEBUG ? err : '',
    });
  }
});

router.post('/', async (req, res) => {
  const { title, author, content, category_name } = req.body;
  let sql = `insert into blogs (title, author, content, category_name ) value('${title}','${author}','${content}','${category_name}')`;
  const { insertId } = await exec(sql);
  res.send({
    code: 0,
    message: '添加成功',
    result: {
      id: insertId,
      title,
      author,
      content,
      category_name,
    },
  });
});

router.put('/:id', async (req, res) => {
  const { id } = req.params;
  const { title, author, content, category_name } = req.body;
  let sql = `update blogs set title='${title}', author='${author}', content='${content}', category_name='${category_name}'   where id=${id} `;
  await exec(sql);
  res.send({
    code: 0,
    message: '修改成功',
    result: {
      id,
      title,
      author,
      content,
      category_name,
    },
  });
});

module.exports = router;
